package com.argticling.dao.impl;

import com.argticling.dao.impl.hibernate.HibernateUtil;
import com.argticling.dao.interf.DublinCoreDAO;
import com.argticling.model.DublinCore;
import com.argticling.model.User;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;

public class DublinCoreDAOImplementation extends AbstractDAOImplementation
		implements DublinCoreDAO {
	public List<DublinCore> getByAuthor(String authorId) {
		List<DublinCore> dublinCore = new ArrayList<DublinCore>();
		Session session = new HibernateUtil().getSession();
		try {
			String query = "from DublinCore where author ='" + authorId + "' ";
			dublinCore = session.createQuery(query).list();
		} finally {
			session.close();
		}
		return dublinCore;

	}

	public List<DublinCore> getBySection(String section) {
		List<DublinCore> dublinCore = new ArrayList<DublinCore>();
		Session session = new HibernateUtil().getSession();
		try {
			String query = "from DublinCore where section ='" + section + "' ";
			dublinCore = session.createQuery(query).list();
		} finally {
			session.close();
		}
		return dublinCore;
	}

	public List<DublinCore> getByDate(String date) {
		
		Session session = new HibernateUtil().getSession();
	    List<DublinCore> dublinCore = session.createQuery("from DublinCore where date = ?").setString(0, date).list();
		return dublinCore;
	}

	public List<DublinCore> getLastArticles() {
		List<DublinCore> dublinCore = new ArrayList<DublinCore>();
		Calendar cal = Calendar.getInstance();
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		dateFormat.format(cal.getTime());
		String date;
		int contador = 0;
		while (dublinCore.size() < 20 && contador < 5) {
			contador++;
			date = dateFormat.format(cal.getTime());
			dublinCore.addAll(getByDate(date));
			cal.add(Calendar.DATE, -1);
		}
		return dublinCore;
	}

	public List<DublinCore> getLastArticles(String section) {
		List<DublinCore> dublinCore = new ArrayList<DublinCore>();
		Calendar cal = Calendar.getInstance();
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		dateFormat.format(cal.getTime());
		String date;
		int contador = 0;
		while (dublinCore.size() < 20 && contador < 5) {
			contador++;
			date = dateFormat.format(cal.getTime());
			dublinCore.addAll(getByDateAndSection(date, section));
			cal.add(Calendar.DATE, -1);
		}
		return dublinCore;
	}

	private List<DublinCore> getByDateAndSection(String date, String section) {
		Session session = new HibernateUtil().getSession();
	    List<DublinCore> dublinCore = session.createQuery("from DublinCore where date = ? and subject = ?").setString(0, date).setString(1, section).list();
		return dublinCore;
	}
}
